<template>
  <view class="friend-stats-page">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">好友心情统计</text>
    </view>

    <!-- 密友信息 -->
    <view class="friend-header-card">
      <view class="friend-avatar-container">
        <text class="friend-avatar">{{ friend.avatar || '👤' }}</text>
      </view>
      <text class="friend-name">{{ friend.nickname }}</text>
      <text class="friend-id">ID: {{ friend.friendId }}</text>
    </view>

    <!-- 心情统计卡片 -->
    <view class="stats-card">
      <text class="card-title">心情统计</text>
      
      <!-- 心情占比（饼图） -->
      <view class="chart-section">
        <view class="chart-header">
          <text class="chart-title">心情分布</text>
          <text class="chart-subtitle">最近30天</text>
        </view>
        <view class="chart-container">
          <qiun-data-charts 
            v-if="pieChartData.series && pieChartData.series.length" 
            type="pie"
            :chartData="pieChartData"
            width="700rpx"
            height="400rpx"
            :opts="pieChartOpts"
            canvasId="friend-pie-chart"
          />
          <view v-else class="no-data-tip">
            <text class="empty-icon">📊</text>
            <text class="empty-text">暂无心情数据</text>
          </view>
        </view>
      </view>

      <!-- 每日心情（柱形图） -->
      <view class="chart-section">
        <view class="chart-header">
          <text class="chart-title">心情趋势</text>
          <text class="chart-subtitle">近7天变化</text>
        </view>
        <view class="chart-container">
          <qiun-data-charts 
            v-if="barChartData.series && barChartData.series.length" 
            type="column"
            :chartData="barChartData"
            width="700rpx"
            height="400rpx"
            :opts="barChartOpts"
            canvasId="friend-bar-chart"
          />
          <view v-else class="no-data-tip">
            <text class="empty-icon">📈</text>
            <text class="empty-text">暂无趋势数据</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 留言功能 -->
    <view class="message-section">
      <text class="section-title">给TA留言</text>
      <textarea 
        v-model="messageContent" 
        placeholder="写下你想对TA说的话..." 
        class="message-input"
        maxlength="100"
        @input="onInput"
      ></textarea>
      <view class="message-footer">
        <text class="char-count">{{ messageContent.length }}/100</text>
        <button class="send-btn" @click="sendMessage" :disabled="!messageContent.trim()">
          <text class="btn-icon">✉️</text>
          发送
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { getStorage, getFriendMessages, saveFriendMessages, getUserInfo } from '@/utils/storage'

export default {
  data() {
    return {
      friend: {
        nickname: '',
        avatar: '',
        friendId: ''
      },
      pieChartData: { series: [] },
      barChartData: { categories: [], series: [] },
      messageContent: '',
      pieChartOpts: {
        type: 'pie',
        padding: [10, 10, 10, 10],
        legend: {
          show: true,
          position: 'bottom',
          align: 'center',
          fontColor: '#666',
          fontSize: 24
        },
        title: {
          name: '心情分布占比',
          fontSize: 28,
          color: '#333'
        },
        pixelRatio: 2,
        forceUtf8Encoding: true,
        pie: {
          innerRadius: 0.5,
          paddingAngle: 2,
          activeScale: 1.05,
          label: {
            show: true,
            fontSize: 22
          }
        }
      },
      barChartOpts: {
        type: 'column',
        padding: [20, 10, 10, 10],
        xAxis: {
          disableGrid: true,
          labelCount: 7,
          fontColor: '#666',
          fontSize: 22
        },
        yAxis: {
          name: '数量',
          nameLocation: 'end',
          gridType: 'dash',
          min: 0,
          fontColor: '#666',
          fontSize: 22
        },
        legend: {
          show: true,
          position: 'bottom',
          fontColor: '#666',
          fontSize: 24
        },
        title: {
          name: '近7天心情趋势',
          fontSize: 28,
          color: '#333'
        },
        pixelRatio: 2,
        forceUtf8Encoding: true,
        column: {
          width: 40,
          activeBgColor: '#2196f3',
          activeBorderColor: '#1976d2'
        }
      }
    }
  },
  onLoad(options) {
    // 模拟获取密友信息和统计数据
    this.friend = {
      nickname: options.nickname,
      avatar: '',
      friendId: options.friendId
    }
    
    // 模拟密友的日记数据（实际项目中应该从服务器获取）
    const mockDiaryList = this.generateMockDiaryData()
    this.initMoodCharts(mockDiaryList)
  },
  methods: {
    // 生成模拟日记数据
    generateMockDiaryData() {
      const tags = ['开心', '疲惫', '学习', '日常', 'emo']
      const mockData = []
      
      // 生成30天的模拟数据
      for (let i = 0; i < 30; i++) {
        const date = new Date()
        date.setDate(date.getDate() - i)
        
        // 每天生成0-2篇日记
        const diaryCount = Math.floor(Math.random() * 3)
        for (let j = 0; j < diaryCount; j++) {
          mockData.push({
            content: `模拟日记内容 ${i}-${j}`,
            tag: tags[Math.floor(Math.random() * tags.length)],
            date: date.toLocaleDateString()
          })
        }
      }
      return mockData
    },
    
    // 发送留言
    sendMessage() {
      if (!this.messageContent.trim()) {
        uni.showToast({ title: '请输入留言内容', icon: 'none' })
        return
      }
      
      // 获取当前用户信息
      const currentUser = getUserInfo()
      
      // 创建新消息
      const newMessage = {
        id: Date.now().toString(),
        senderId: currentUser.userId,
        senderName: currentUser.nickname,
        senderAvatar: currentUser.avatar,
        content: this.messageContent.trim(),
        time: new Date().toISOString(),
        read: false,
        friendId: this.friend.friendId
      }
      
      // 获取现有消息列表
      const messages = getFriendMessages()
      
      // 添加新消息到列表开头
      messages.unshift(newMessage)
      
      // 保存消息列表
      saveFriendMessages(messages)
      
      // 显示发送成功提示
      uni.showToast({
        title: '留言发送成功',
        icon: 'success',
        duration: 1500
      })
      
      // 清空输入框
      this.messageContent = ''
      
      // 可以考虑添加一个导航到消息中心的提示或直接跳转到消息中心
    },
    
    // 初始化心情图表
    initMoodCharts(diaryList) {
      const moodColorMap = {
        开心: '#FF6B6B',
        疲惫: '#4ECDC4',
        学习: '#FFD166',
        日常: '#6A0572',
        emo: '#1A535C'
      }
      
      // 饼图数据处理
      const moodCount = {
        开心: 0,
        疲惫: 0,
        学习: 0,
        日常: 0,
        emo: 0
      }
      
      diaryList.forEach(diary => {
        if (diary.tag && moodCount[diary.tag] !== undefined) {
          moodCount[diary.tag]++
        }
      })
      
      const pieSeries = Object.entries(moodCount)
        .filter(([mood, count]) => count > 0)
        .map(([mood, count]) => ({
          name: mood,
          data: count,
          color: moodColorMap[mood]
        }))
        
      this.pieChartData = {
        series: pieSeries
      }
      
      // 柱形图数据处理
      const last7Days = this.getLast7Days()
      const dailyMoodData = last7Days.reduce((obj, day) => {
        obj[day] = {
          开心: 0,
          疲惫: 0,
          学习: 0,
          日常: 0,
          emo: 0
        }
        return obj
      }, {})
      
      diaryList.forEach(diary => {
        if (diary.date && diary.tag) {
          const diaryDate = this.formatDateToMd(diary.date)
          if (last7Days.includes(diaryDate) && dailyMoodData[diaryDate][diary.tag] !== undefined) {
            dailyMoodData[diaryDate][diary.tag]++
          }
        }
      })
      
      const barSeries = Object.entries(moodColorMap)
        .map(([mood, color]) => ({
          name: mood,
          data: last7Days.map(day => dailyMoodData[day][mood] || 0),
          color: color
        }))
        .filter(series => series.data.some(num => num > 0))
        
      this.barChartData = {
        categories: last7Days,
        series: barSeries
      }
    },
    
    // 获取近7天日期
    getLast7Days() {
      return Array(7).fill().map((_, i) => {
        const date = new Date()
        date.setDate(date.getDate() - 6 + i)
        return this.formatDateToMd(date)
      })
    },
    
    // 格式化日期为月-日
    formatDateToMd(date) {
      if (typeof date === 'string') {
        const parts = date.split('/')
        if (parts.length === 3) {
          const month = parseInt(parts[1], 10)
          const day = parseInt(parts[2], 10)
          return `${month}-${day}`
        }
      } else if (date instanceof Date) {
        return `${date.getMonth() + 1}-${date.getDate()}`
      }
      return ''
    },
    
    // 输入事件处理
    onInput(e) {
      this.messageContent = e.detail.value
    },
    
    // 发送留言
    sendMessage() {
      if (!this.messageContent.trim()) {
        return
      }
      
      // 模拟发送留言（实际项目中应该发送到服务器）
      uni.showToast({ title: '留言发送成功', icon: 'success' })
      this.messageContent = ''
    }
  }
}
</script>

<style scoped>
.friend-stats-page {
  padding: 20rpx;
  min-height: 100vh;
  background: linear-gradient(135deg, #e3f2fd, #bbdefb);
}

/* 页面标题 */
.page-header {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  text-align: center;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

/* 密友信息 */
.friend-header-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25rpx;
  padding: 40rpx 20rpx;
  margin-bottom: 25rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10rpx);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15rpx;
}

.friend-avatar-container {
  position: relative;
  margin-bottom: 10rpx;
}

.friend-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #2196f3, #1976d2);
  color: white;
  font-size: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 30rpx rgba(33, 150, 243, 0.4);
  transition: all 0.3s ease;
}

.friend-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 5rpx;
}

.friend-id {
  font-size: 24rpx;
  color: #666;
  background: rgba(33, 150, 243, 0.1);
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
}

/* 统计卡片 */
.stats-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25rpx;
  padding: 30rpx;
  margin-bottom: 25rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10rpx);
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  text-align: center;
}

/* 图表区域 */
.chart-section {
  margin-bottom: 40rpx;
  padding: 25rpx;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 20rpx;
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.05);
}

.chart-section:last-child {
  margin-bottom: 0;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.chart-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
}

.chart-subtitle {
  font-size: 24rpx;
  color: #666;
  background: rgba(33, 150, 243, 0.1);
  padding: 6rpx 16rpx;
  border-radius: 15rpx;
}

.chart-container {
  display: flex;
  justify-content: center;
  min-height: 400rpx;
  align-items: center;
  padding: 20rpx;
  background: white;
  border-radius: 15rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 无数据提示 */
.no-data-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20rpx;
  color: #999;
}

.empty-icon {
  font-size: 80rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 28rpx;
  background: rgba(33, 150, 243, 0.1);
  padding: 15rpx 30rpx;
  border-radius: 25rpx;
}

/* 留言区域 */
.message-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 25rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10rpx);
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 25rpx;
}

.message-input {
  width: 100%;
  height: 180rpx;
  border: 2rpx solid rgba(33, 150, 243, 0.3);
  border-radius: 20rpx;
  padding: 25rpx;
  margin-bottom: 20rpx;
  font-size: 26rpx;
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
  resize: none;
}

.message-input:focus {
  outline: none;
  border-color: rgba(33, 150, 243, 0.8);
  box-shadow: 0 0 0 5rpx rgba(33, 150, 243, 0.1);
}

.message-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.char-count {
  font-size: 24rpx;
  color: #666;
  background: rgba(33, 150, 243, 0.1);
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
}

.send-btn {
  background: linear-gradient(135deg, #2196f3, #1976d2);
  color: white;
  border-radius: 50rpx;
  padding: 25rpx 45rpx;
  font-size: 28rpx;
  border: none;
  outline: none;
  box-shadow: 0 4rpx 15rpx rgba(33, 150, 243, 0.3);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 12rpx;
  min-width: 120rpx;
  justify-content: center;
}

.send-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 10rpx rgba(33, 150, 243, 0.2);
}

.send-btn:disabled {
  background: linear-gradient(135deg, #ccc, #999);
  box-shadow: none;
  opacity: 0.7;
}

.btn-icon {
  font-size: 30rpx;
}
</style>